/**
 * 
 */
package com.munoor.dalai.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.munoor.dalai.client.DalaiServer;
import com.munoor.dalai.client.event.AJAXCallEvent;
import com.munoor.dalai.client.event.AJAXReturnEvent;
import com.munoor.dalai.client.event.LoginEvent;
import com.munoor.dalai.client.misc.Marshaller;

/**
 * @author Osho
 * 
 */
public class LoginPresenter implements Presenter {
	private final Display display;

	public interface Display {
		HasClickHandlers getLoginButton();
		String getUsername();
		String getPassword();
		void setSignInError(String error);
		Widget asWidget();
	}

	public LoginPresenter(SimpleEventBus eventBus, Display display) {
		this.display = display;
		bind();
	}

	public void bind() {

		this.display.getLoginButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doLogin();
			}
		});

		/*this.display.getSignUpButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doSignUp();
			}
		});*/

	}

	@Override
	public void go(HasWidgets container) {
	    container.clear();
	    container.add(display.asWidget());
	}

	private void doLogin() {
		display.setSignInError("");
		if (display.getUsername().length() < 1)	{
			display.setSignInError("Empty Username");
			return;
		}
		if (display.getPassword().length() < 1){
			display.setSignInError("Empty Password");
			return;
		}
		
		DalaiServer.get().getUser().setUsername(display.getUsername());
		DalaiServer.get().getUser().setPassword(display.getPassword());
		
		DalaiServer.get().getEventBus().fireEvent(new AJAXCallEvent());
		RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, "/login");
		rb.setHeader("Content-Type", "application/json");
		rb.setHeader("Accept", "application/json");
		try{
            rb.sendRequest(Marshaller.marshallUser(DalaiServer.get().getUser()), new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                	DalaiServer.get().getEventBus().fireEvent(new AJAXReturnEvent());
					// setMessageText("Error");
					GWT.log("REST call error");
                }
                public void onResponseReceived(Request request, Response response) {
                	DalaiServer.get().getEventBus().fireEvent(new AJAXReturnEvent());
                	//401 or 200
                	if (response.getStatusCode() == 200){
                		//passed
                		JSONObject userObject = ((JSONParser.parseStrict(response.getText())).isObject());
                		DalaiServer.get().getUser().setEmail(userObject.get("email").isString().stringValue());              		
                		DalaiServer.get().getUser().setLastScan((long)(userObject.get("lastScan").isNumber().doubleValue()));
                		DalaiServer.get().getUser().setLastScan((long)(userObject.get("userId").isNumber().doubleValue()));
                		DalaiServer.get().getUser().setLastScan((short)(userObject.get("userType").isNumber().doubleValue()));
                		DalaiServer.get().getEventBus().fireEvent(new LoginEvent()); 		
                	}else{
                		display.setSignInError("Login failed");
                	}
                }
            });
		}catch(RequestException e){
			
		}	
	}
/*	private void doSignUp() {
		// Window.Location.assign("/logingoogle");
		GWT.log("Signup Clicked");
	}*/
}
